import 'dart:convert';
import 'dart:io';

import 'package:fluent_ui/fluent_ui.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 配置类，用于表示单个配置
class ThemeConfiguration {
  String id;
  String name;
  bool isDark;
  AccentColor color;
  String workspaceDir;
  String outputDir;
  
  ThemeConfiguration({
    required this.id,
    required this.name,
    required this.isDark,
    required this.color,
    required this.workspaceDir,
    required this.outputDir,
  });
  
  // 从JSON创建配置对象
  factory ThemeConfiguration.fromJson(Map<String, dynamic> json) {
    return ThemeConfiguration(
      id: json['id'],
      name: json['name'],
      isDark: json['isDark'] ?? false,
      color: _stringToAccentColor(json['color']),
      workspaceDir: json['workspaceDir'] ?? '',
      outputDir: json['outputDir'] ?? '',
    );
  }
  
  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'isDark': isDark,
      'color': color.toString(),
      'workspaceDir': workspaceDir,
      'outputDir': outputDir,
    };
  }
  
  // 将字符串转换为AccentColor
  static AccentColor _stringToAccentColor(String? colorStr) {
    var accentColors = Colors.accentColors;
    for(var color in accentColors) {
      if(colorStr == color.toString()){
        return color;
      }
    }
    return Colors.blue;
  }
}

class ThemeController extends GetxController {
  late SharedPreferences _prefs;
  
  // 当前活跃的配置
  final Rx<ThemeConfiguration?> currentConfig = Rx<ThemeConfiguration?>(null);
  
  // 所有配置列表
  final RxList<ThemeConfiguration> configurations = RxList<ThemeConfiguration>([]);
  
  // 当前使用的配置ID
  final RxString activeConfigId = RxString('');

  @override
  void onInit() {
    super.onInit();
    _initPrefs();
  }

  Future<void> _initPrefs() async {
    _prefs = await SharedPreferences.getInstance();
    
    // 加载配置列表
    _loadConfigurations();
    
    // 加载当前活跃配置ID
    activeConfigId.value = _prefs.getString('activeConfigId') ?? '';
    
    // 兼容旧配置
    if (configurations.isEmpty) {
      _migrateFromOldConfig();
    }
    
    // 设置当前活跃配置
    if (activeConfigId.value.isNotEmpty) {
      currentConfig.value = configurations.firstWhere(
        (config) => config.id == activeConfigId.value,
        orElse: () => _getDefaultConfiguration(),
      );
    } else if (configurations.isNotEmpty) {
      currentConfig.value = configurations.first;
      activeConfigId.value = currentConfig.value!.id;
      _prefs.setString('activeConfigId', activeConfigId.value);
    } else {
      currentConfig.value = _getDefaultConfiguration();
      if (currentConfig.value != null) {
        configurations.add(currentConfig.value!);
        activeConfigId.value = currentConfig.value!.id;
        _saveConfigurations();
        _prefs.setString('activeConfigId', activeConfigId.value);
      }
    }
  }
  
  // 从旧配置迁移
  void _migrateFromOldConfig() {
    bool oldIsDark = _prefs.getBool('isDark') ?? false;
    AccentColor oldColor = _stringToAccentColor(_prefs.getString("color")) ?? Colors.blue;
    String oldWorkspaceDir = _prefs.getString("workspaceDir") ?? "";
    String oldOutputDir = _prefs.getString("outputDir") ?? "";
    
    // 尝试从旧的config字段获取配置
    final configString = _prefs.getString('config');
    if (configString != null) {
      final config = jsonDecode(configString);
      if(config['workspaceDir'] != null && oldWorkspaceDir == ""){
        oldWorkspaceDir = config['workspaceDir'] ?? "";
      }
    }
    
    // 如果工作空间为空，设置默认值
    if (oldWorkspaceDir.isEmpty) {
      String mainPath = Platform.resolvedExecutable;
      mainPath = mainPath.substring(0, mainPath.lastIndexOf("\\"));
      String defaultWorkspaceDir = "$mainPath${Platform.pathSeparator}workspace";
      
      Directory defaultWorkspace = Directory(defaultWorkspaceDir);
      if(!defaultWorkspace.existsSync()){
        defaultWorkspace.createSync();
      }
      oldWorkspaceDir = defaultWorkspaceDir;
    }
    
    // 如果输出目录为空，设置默认值
    if (oldOutputDir.isEmpty) {
      String mainPath = Platform.resolvedExecutable;
      mainPath = mainPath.substring(0, mainPath.lastIndexOf("\\"));
      String defaultOutputDirPath = "$mainPath${Platform.pathSeparator}output";
      
      Directory defaultOutputDir = Directory(defaultOutputDirPath);
      if(!defaultOutputDir.existsSync()){
        defaultOutputDir.createSync();
      }
      oldOutputDir = defaultOutputDirPath;
    }
    
    // 创建默认配置
    var defaultConfig = ThemeConfiguration(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      name: '默认配置',
      isDark: oldIsDark,
      color: oldColor,
      workspaceDir: oldWorkspaceDir,
      outputDir: oldOutputDir,
    );
    
    configurations.add(defaultConfig);
    currentConfig.value = defaultConfig;
    activeConfigId.value = defaultConfig.id;
    
    _saveConfigurations();
    _prefs.setString('activeConfigId', activeConfigId.value);
  }
  
  // 获取默认配置
  ThemeConfiguration _getDefaultConfiguration() {
    String mainPath = Platform.resolvedExecutable;
    mainPath = mainPath.substring(0, mainPath.lastIndexOf("\\"));
    
    String defaultWorkspaceDir = "$mainPath${Platform.pathSeparator}workspace";
    Directory defaultWorkspace = Directory(defaultWorkspaceDir);
    if(!defaultWorkspace.existsSync()){
      defaultWorkspace.createSync();
    }
    
    String defaultOutputDirPath = "$mainPath${Platform.pathSeparator}output";
    Directory defaultOutputDir = Directory(defaultOutputDirPath);
    if(!defaultOutputDir.existsSync()){
      defaultOutputDir.createSync();
    }
    
    return ThemeConfiguration(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      name: '默认配置',
      isDark: false,
      color: Colors.blue,
      workspaceDir: defaultWorkspaceDir,
      outputDir: defaultOutputDirPath,
    );
  }
  
  // 加载配置列表
  void _loadConfigurations() {
    final configsJson = _prefs.getString('configurations');
    if (configsJson != null) {
      final List<dynamic> configsList = jsonDecode(configsJson);
      configurations.assignAll(configsList.map((json) => ThemeConfiguration.fromJson(json)).toList());
    }
  }
  
  // 保存配置列表
  void _saveConfigurations() {
    final configsJson = jsonEncode(configurations.map((config) => config.toJson()).toList());
    _prefs.setString('configurations', configsJson);
  }

  // 获取当前配置属性（提供计算属性）
  bool get isDark => currentConfig.value?.isDark ?? false;
  AccentColor get color => currentConfig.value?.color ?? Colors.blue;
  String get workspaceDir => currentConfig.value?.workspaceDir ?? '';
  String get outputDir => currentConfig.value?.outputDir ?? '';
  String get currentConfigName => currentConfig.value?.name ?? '默认配置';
  
  // 通过名称获取配置
  ThemeConfiguration? getConfigByName(String configName) {
    return configurations.firstWhereOrNull((config) => config.name == configName);
  }
  
  // 将字符串转换为AccentColor
  AccentColor _stringToAccentColor(String? color){
    var accentColors = Colors.accentColors;
    for(var value in accentColors) {
      if(color == value.toString()){
        return value;
      }
    }
    return Colors.blue;
  }

  /**
   * 设置主题颜色
   */
  void setThemeColor(AccentColor color) {
    if (currentConfig.value != null) {
      currentConfig.value!.color = color;
      _saveConfigurations();
      print('设置主题颜色: $color');
      // 先刷新当前配置
      currentConfig.refresh();
      // 确保GetX也更新
      update();
    }
  }

  void toggleTheme() {
    if (currentConfig.value != null) {
      currentConfig.value!.isDark = !currentConfig.value!.isDark;
      _saveConfigurations();
      currentConfig.refresh(); // 通知观察者更新
      update(); // 确保GetX也更新
      print('主题模式已切换: ${currentConfig.value!.isDark ? '暗黑模式' : '明亮模式'}');
    }
  }

  /**
   * 设置工作空间
   */
  void setWorkspaceDir(String workspace) {
    if (currentConfig.value != null) {
      currentConfig.value!.workspaceDir = workspace;
      _saveConfigurations();
      currentConfig.refresh(); // 通知观察者更新
    }
  }

  /**
   * 设置输出目录
   */
  void setOutputDir(String outputDir) {
    if (currentConfig.value != null) {
      currentConfig.value!.outputDir = outputDir;
      _saveConfigurations();
      currentConfig.refresh(); // 通知观察者更新
    }
  }
  
  /**
   * 创建新配置
   */
  void createConfiguration(String name, {Map<String, dynamic>? configData}) {
    // 确保配置名称唯一
    String uniqueName = name;
    int counter = 1;
    while (configurations.any((config) => config.name == uniqueName)) {
      uniqueName = '$name ($counter)';
      counter++;
    }
    
    var newConfig = ThemeConfiguration(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      name: uniqueName,
      isDark: configData?['isDark'] ?? currentConfig.value?.isDark ?? false,
      color: _stringToAccentColor(configData?['color']) ?? currentConfig.value?.color ?? Colors.blue,
      workspaceDir: configData?['workspaceDir'] ?? currentConfig.value?.workspaceDir ?? '',
      outputDir: configData?['outputDir'] ?? currentConfig.value?.outputDir ?? '',
    );
    
    configurations.add(newConfig);
    _saveConfigurations();
  }
  
  /**
   * 删除配置
   */
  void deleteConfiguration(String configId) {
    if (configId == activeConfigId.value) {
      // 不能删除当前活跃的配置
      return;
    }
    
    configurations.removeWhere((config) => config.id == configId);
    _saveConfigurations();
  }
  
  /**
   * 切换配置
   */
  void switchConfiguration(String configId) {
    final newConfig = configurations.firstWhere(
      (config) => config.id == configId,
      orElse: () => currentConfig.value!,
    );
    
    if (newConfig != currentConfig.value) {
      currentConfig.value = newConfig;
      activeConfigId.value = configId;
      _prefs.setString('activeConfigId', activeConfigId.value);
      currentConfig.refresh(); // 通知观察者更新
      print('已切换到配置: ${newConfig.name}, ID: ${newConfig.id}');
    }
  }
  
  /**
   * 通过名称切换配置
   */
  void switchConfigurationByName(String configName) {
    final newConfig = getConfigByName(configName);
    if (newConfig != null && newConfig != currentConfig.value) {
      currentConfig.value = newConfig;
      activeConfigId.value = newConfig.id;
      _prefs.setString('activeConfigId', activeConfigId.value);
      currentConfig.refresh(); // 通知观察者更新
      print('已通过名称切换到配置: ${newConfig.name}, ID: ${newConfig.id}');
    }
  }
  
  /**
   * 重命名配置
   */
  void renameConfiguration(String configId, String newName) {
    final configIndex = configurations.indexWhere((config) => config.id == configId);
    if (configIndex != -1) {
      // 确保新名称唯一
      String uniqueName = newName;
      int counter = 1;
      while (configurations.any((config) => config.id != configId && config.name == uniqueName)) {
        uniqueName = '$newName ($counter)';
        counter++;
      }
      
      configurations[configIndex].name = uniqueName;
      _saveConfigurations();
      
      // 如果是当前配置，更新当前配置引用
      if (currentConfig.value != null && currentConfig.value!.id == configId) {
        currentConfig.refresh();
      }
    }
  }
}